/*
 *  This file is part of Bracket Security
 *  Copyright 2011 David R. Smith
 *
 */
package asia.redact.bracket.util;

import java.io.IOException;
import java.nio.charset.Charset;

import net.iharder.Base64;

/**
 * <pre>
 * Wrapper to provide a type for Base64 encoded url-safe variant Strings. These Strings
 * can be in URLs, whereas normal Base64 strings can contain / which is a problem.
 * 
 * A more accurate name for this class might be "ArmoredString" but SafeString is easier on the tongue.
 * </pre>
 * @author Dave
 *
 */
public class SafeString {
	
	private String encoded;
	
	public SafeString() {
		super();
		encoded = "";
	}
	
	public SafeString(byte [] unencoded){
		try {
			encoded = Base64.encodeBytes(unencoded, Base64.URL_SAFE);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * Probably assumes UTF-8 encoding as input
	 * 
	 * @param unencoded
	 */
	public SafeString(String unencoded) {
		try {
			encoded = Base64.encodeBytes(unencoded.getBytes(), Base64.URL_SAFE);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	
	public String toString() {
		return encoded;
	}
	
	public byte [] decode() {
		try {
			return Base64.decode(encoded,Base64.URL_SAFE);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	
	public String decode(Charset charset) {
		byte[] bytes;
		try {
			bytes = Base64.decode(encoded,Base64.URL_SAFE);
			return new String(bytes, charset);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		
	}

	public String getEncoded() {
		return encoded;
	}

	public void setEncoded(String encoded) {
		this.encoded = encoded;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((encoded == null) ? 0 : encoded.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (!(obj instanceof SafeString)) {
			return false;
		}
		SafeString other = (SafeString) obj;
		if (encoded == null) {
			if (other.encoded != null) {
				return false;
			}
		} else if (!encoded.equals(other.encoded)) {
			return false;
		}
		return true;
	}

}
